package com.learn.demo.action;

import com.learn.demo.service.ModifyService;
import com.learn.demo.service.QueryService;
import com.learn.springframework.annotation.Autowired;
import com.learn.springframework.annotation.Controller;
import com.learn.springframework.annotation.RequestMapping;
import com.learn.springframework.annotation.RequestParam;
import com.learn.springframework.v3.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/web")
public class MyAction {

    @Autowired
    private QueryService queryService;

    @Autowired
    private ModifyService modifyService;

    // http://localhost:8089/web/remove.json?id=2
    @RequestMapping("/query.json")
    public ModelAndView query(HttpServletRequest request, HttpServletResponse response, @RequestParam("name") String name) {
        String result = queryService.query(name);
        return out(response, result);
    }

    @RequestMapping("/add*.json")
    public ModelAndView add(HttpServletRequest req, HttpServletResponse response
            , @RequestParam("name") String name, @RequestParam("addr") String addr) throws Exception {
        String result = modifyService.add(name, addr);
        return out(response, result);
    }

    @RequestMapping("/remove.json")
    public ModelAndView remove(HttpServletRequest req, HttpServletResponse resp, @RequestParam("id") Integer id) {
        String result = modifyService.remove(id);
        return out(resp, result);
    }

    @RequestMapping("/edit.json")
    public ModelAndView edit(HttpServletRequest req, HttpServletResponse resp, @RequestParam("id") Integer id, @RequestParam("name") String name) {
        String edit = modifyService.edit(id, name);
        return out(resp, edit);
    }

    private ModelAndView out(HttpServletResponse response, String str) {
        try {
            response.getWriter().write(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
